import { requestClient, baseRequestClient } from '#/api/request';
import { useAccessStore } from '@vben/stores';

export namespace InvoiceApi {
  /** 发票列表查询参数 */
  export interface InvoiceListParams {
    page?: number;
    per_page?: number;
    invoice_id?: string;
    billing_type?: '6_regular' | '6_special' | 'differential_regular';
    landing_company_id?: number;
    billing_category?: 'it_services';
    status?: string;
    start_date?: string;
    end_date?: string;
    sort_by?: string;
    sort_order?: 'asc' | 'desc';
  }

  /** 发票记录接口 */
  export interface InvoiceRecord {
    id: string;
    invoice_id: string;
    invoice_number: string;
    tenant_id: number;
    landing_company_id: number;
    invoice_amount: number;
    billing_type: '6_regular' | '6_special' | 'differential_regular';
    billing_type_display: string;
    billing_category: 'it_services';
    billing_category_display: string;
    invoice_title: string;
    tax_number: string;
    company_address?: string;
    company_phone?: string;
    bank_name?: string;
    bank_account?: string;
    invoice_content: string;
    related_tasks?: string;
    invoice_file_path?: string | null;
    status: '新建' | '开票中' | '已开票' | '已拒绝' | '已作废';
    status_display?: string;
    rejection_reason?: string;
    express_tracking_number?: string;
    invoice_remarks?: string;
    application_time: string;
    processed_at?: string;
    issued_at?: string;
    created_by?: number;
    processed_by?: number;
    created_at: string;
    updated_at: string;
    landing_company?: {
      id: number;
      name: string;
      short_name?: string;
      code: string;
    };
  }

  /** 租户开票信息接口 */
  export interface TenantBillingInfo {
    company_name: string | null;
    tax_registration_number: string | null;
    address: string | null;
    bank_name: string | null;
    bank_account: string | null;
    invoice_contact_phone: string | null;
    invoice_mailing_address: string | null;
    invoice_recipient: string | null;
    invoiceable_amount: number;
    formatted_invoiceable_amount: string;
  }

  /** 落地公司选项 */
  export interface LandingCompanyOption {
    value: number;
    label: string;
    name: string;
    code: string;
  }

  /** 选项接口 */
  export interface SelectOption {
    value: string | number;
    label: string;
  }

  /** 分页响应结构 */
  export interface InvoiceListResponse {
    data: InvoiceRecord[];
    current_page: number;
    per_page: number;
    total: number;
    last_page: number;
    from: number | null;
    to: number | null;
    first_page_url: string | null;
    last_page_url: string | null;
    next_page_url: string | null;
    prev_page_url: string | null;
    path: string | null;
    links: Array<{
      url: string | null;
      label: string;
      active: boolean;
    }>;
  }

  /** API响应包装 */
  export interface ApiResponse<T = any> {
    success: boolean;
    data: T;
    message?: string;
    error?: any;
  }

  export interface CreateInvoicePayload {
    landing_company_id: number;
    invoice_amount: number;
    billing_type: '6_regular' | '6_special' | 'differential_regular';
    billing_category: string;
    invoice_content?: string;
    related_tasks?: string | string[];
    invoice_remarks?: string;
  }
}

/**
 * 获取发票列表
 * @param params 查询参数
 * @returns 发票列表响应数据
 */
export async function getInvoiceListApi(params: InvoiceApi.InvoiceListParams) {
  return requestClient.get<InvoiceApi.InvoiceListResponse>('/api/tenant/invoices', {
    params,
  });
}

/**
 * 获取租户开票信息
 */
export async function getTenantBillingInfoApi() {
  return requestClient.get<InvoiceApi.TenantBillingInfo>('/api/tenant/billing-info');
}

/**
 * 获取落地公司选项
 */
export async function getLandingCompanyOptionsApi() {
  return requestClient.get<InvoiceApi.LandingCompanyOption[]>('/api/tenant/landing-companies/options');
}

/**
 * 获取开票类型选项
 */
export async function getBillingTypeOptionsApi() {
  return requestClient.get<InvoiceApi.SelectOption[]>('/api/tenant/invoices/billing-type-options');
}

/**
 * 获取开票类目选项
 */
export async function getBillingCategoryOptionsApi() {
  return requestClient.get<InvoiceApi.SelectOption[]>('/api/tenant/invoices/billing-category-options');
}

/**
 * 获取开票状态选项
 */
export async function getInvoiceStatusOptionsApi() {
  return requestClient.get<InvoiceApi.SelectOption[]>('/api/tenant/invoices/status-options');
}

/**
 * 获取发票详情
 */
export async function getInvoiceDetailApi(id: string) {
  return requestClient.get<InvoiceApi.ApiResponse<InvoiceApi.InvoiceRecord>>(`/api/tenant/invoices/${id}`);
}

/**
 * 创建发票申请
 */
export async function createInvoiceApi(data: InvoiceApi.CreateInvoicePayload) {
  return requestClient.post<InvoiceApi.InvoiceRecord>('/api/tenant/invoices', data);
}

/**
 * 更新发票申请
 */
export async function updateInvoiceApi(id: string, data: Partial<InvoiceApi.InvoiceRecord>) {
  return requestClient.put<InvoiceApi.InvoiceRecord>(`/api/tenant/invoices/${id}`, data);
}

/**
 * 删除发票申请
 */
export async function deleteInvoiceApi(id: string) {
  return requestClient.delete(`/api/tenant/invoices/${id}`);
}

export async function downloadInvoiceFileApi(id: string) {
  const accessStore = useAccessStore();
  const token = accessStore.accessToken;

  const response = await baseRequestClient.get(`/api/tenant/invoices/${id}/download`, {
    responseType: 'blob',
    headers: token ? { Authorization: `Bearer ${token}` } : undefined,
  });

  return response.data as Blob;
}

/**
 * 保存或更新租户开票信息
 */
export async function saveTenantBillingInfoApi(data: Partial<InvoiceApi.TenantBillingInfo>) {
  return requestClient.post<InvoiceApi.TenantBillingInfo>('/api/tenant/billing-info', data);
}

/**
 * 获取落地公司开票类目列表
 */
export async function getBillingCategoriesListApi() {
  return requestClient.get<Array<{
    company_id: number;
    company_name: string;
    categories: string[];
  }>>('/api/tenant/landing-companies/billing-categories');
}
